package cn.houjunxiong.plugins.vp;

import android.annotation.SuppressLint;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaMetadata;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.ui.PlayerView;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.houjunxiong.plugins.vp.databinding.ActivityVideoPlayerBinding;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class VideoPlayerActivity extends FragmentActivity {
    private ExoPlayer player;

    @RequiresApi(api = 34)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_video_player);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        PlayerView playerView = findViewById(R.id.player_view);

        player = new ExoPlayer.Builder(this.getApplicationContext()).build();
        playerView.setPlayer(player);

        Intent intent = getIntent();
        int index = intent.getIntExtra("index", 0);
        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<VideoPlayer.Video>>(){}.getType();
        List<VideoPlayer.Video> videos = gson.fromJson(intent.getStringExtra("videos"), type);

        if (videos != null && !videos.isEmpty()) {
            List<MediaItem> items = videos.stream().map(video -> {
                MediaItem.Builder builder = new MediaItem.Builder();
                builder.setUri(video.url).setMediaId(video.title);
                builder.setMediaMetadata(new MediaMetadata.Builder()
                        .setTitle(video.title)
                        .build());
                return builder.build();
            }).toList();
            player.addMediaItems(items);
        }

        player.prepare();
        player.play();
    }

    @Override
    protected void onDestroy() {
        player.stop();
        super.onDestroy();
    }
}